<?php
/**
 * 工单签收操作
 * User: Administrator
 * Date: 2018\8\8 0008
 * Time: 9:37
 */

namespace app\lib\Order\OrderOption;


use app\lib\Order\OrderExtensionConfig\GetOrderBindingExtension;
use app\lib\Order\OrderExtensionConfig\OrderBindingEditExtension;
use app\lib\Order\OrderPaymentNotice\OrderNotice;
use app\lib\Order\OrderSign\AddOrderSignImg;
use app\lib\Order\OrderSign\EditOrderSignRecord;
use app\lib\Order\OrderSign\GetOrderSignRecord;

class OrderSignOption
{
    protected  $orderId;
    protected  $signId;
    protected  $type;
    protected  $img;
    protected  $opUid;
    public function __construct($orderId,$signId)
    {
       $this->orderId = $orderId;
       $this->signId  = $signId;
    }

    public function setOpUid($opUid){
        $this->opUid = $opUid;
        return $this;
    }
    public function setType($type){
        $this->type = $type;
        return $this;
    }

    public function setImg($img){
        $this->img  = $img;
        return $this;
    }

    /**
     * 参数验证
     * @return bool
     * @throws \Exception
     */
    private function check(){
        /*该工单是否存在未签收记录*/
        if((new GetOrderSignRecord($this->signId))->IsSign()){
            exception('已经被签收了，无法再进行签收');
        }
        /*操作人不能为空*/
        if(empty($this->opUid) || !is_numeric($this->opUid)){
            exception('未获取到操作人或者操作人类型错误');
        }
        /*操作类型不能为空*/
        if(empty($this->type) || in_array($this->type,['sys','user'])){
            exception('未获取到操作类型或者操作类型错误');
        }
        if($this->type =='sys' && empty($this->img)){
            exception('代签收需要客户签字照片');
        }
        return true;
    }

    /**
     * 签收操作
     * @return bool
     * @throws \Exception
     */
    public function save(){
        $this->check();
        /*修改签收状态*/
        (new EditOrderSignRecord($this->signId,$this->opUid))->setType($this->type)->save();
        /*记录图片*/
        if($this->img){
            (new AddOrderSignImg($this->signId,$this->opUid,$this->img))->save();
        }
        /*判断是否存在未签收标签*/
        $model =  new GetOrderBindingExtension($this->orderId);
        if(!$model->isOrderBindingSign()){
            return true;
        }
        /*取消标签*/
        $orderBinding = new OrderBindingEditExtension($this->orderId,'sign','验收完成，取消标签');
        $orderBinding->releaseBinding();
        $content = (new OrderNotice($this->orderId))->getMaxIdSignNoticeName();
        $str = '验收人:'.$this->type=='sys'?'后台代验收':'用户自己';
        /*记录工单日志*/
        $log =  (new OrderOptionLog($this->orderId));
        $log->setOptionType('SIGNTASK');
        $log->setOptionUserId($this->opUid);
        $log->setOptionContent('验收操作:【'.$content.'】,'.$str);
        $log->save();
        return true;
    }


}